package com.yellow.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yellow.pojo.Permission;
import com.yellow.pojo.Role;
import com.yellow.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityService implements UserDetailsService {

    //Dubbo 调用服务
    @Reference
    private UserService userService;

    //使用安全框架调用该方法
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findUserByUserName(username);

        if (user == null) {
            //用户不存在
            return null;
        }

        //获取用户的角色和权限
        List<GrantedAuthority> list = new ArrayList<>();
        Set<Role> roles = user.getRoles();
        //获取用户的角色
        for (Role role : roles) {
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            //获取对应角色拥有的权限
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
//                System.out.println("permission---keyword = " +0 permission.getKeyword());
            }
        }
        org.springframework.security.core.userdetails.User userdetails =
                new org.springframework.security.core.userdetails.User(username, user.getPassword(), list);

        return userdetails;
    }
}
